import axios from "axios";
import config from "@/config";
import { ElMessage } from "element-plus";
import { useToken } from "@/stores/token";
import router from "@/router";
const tokenStore = useToken();
const baseURL = config.baseURL;
const service = axios.create({ baseURL });
service.interceptors.request.use(
  (config) => {
    const token = tokenStore.token;
    if (token) {
      config.headers.jwt = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
service.interceptors.response.use(
  (response) => {
    if (response.data.errno == 2) {
      ElMessage.error(response.data.errmsg);
      router.push("/login");
    }
    return response;
  },
  (_error) => {
    ElMessage({ type: "error", message: "网络请求失败..." });
    return Promise.resolve({});
  }
);
export default service;
